import os
import shutil
import stat
from pathlib import Path
from tempfile import NamedTemporaryFile

from fastapi import UploadFile

from util.ErrorCode import ErrorCode
from util.LogHelper import Log


def upload_file(path: str, file: UploadFile):
    SAVE_PATH = './resource/static/files/' + path
    if not os.path.exists(SAVE_PATH):
        os.makedirs(SAVE_PATH)
    try:
        suffix = Path(file.filename).suffix
        with NamedTemporaryFile(delete=False, suffix=suffix, dir=SAVE_PATH) as tmp:
            shutil.copyfileobj(file.file, tmp)
            tmp_file_name = Path(tmp.name).name
            os.chmod(SAVE_PATH + f'/{tmp_file_name}', stat.S_IRWXU+stat.S_IRGRP+stat.S_IXGRP+stat.S_IROTH)
            result = {'url': path + f'/{tmp_file_name}'}
            return {'code': ErrorCode.SUCCESS.value, 'message': 'success', 'data': result}
    except Exception as e:
        Log.getlogger().error(f'upload_file failed! message: {e}')
        return {'code': ErrorCode.UPLOAD_FILE_FAILED.value, 'message': 'Upload file failed!'}
    finally:
        file.file.close()
